package com.heima.springai.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.heima.springai.repository.IChatHistoryService;
import com.heima.springai.entity.vo.MessageVo;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.content.Media;
import org.springframework.util.MimeType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Objects;

/**
 * @author 噤玥
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/ai")
public class ChatController {
    @Resource
    private ChatClient chatClient;
    @Resource
    private IChatHistoryService chatHistoryService;
    private final ChatMemory chatMemory;
    @RequestMapping(value = "/chat",produces = "text/html;charset=utf-8")
    public Flux<String> chat(
            @RequestParam("prompt") String prompt,
            @RequestParam("chatId") String chatId,
            @RequestParam(value = "files", required = false) List<MultipartFile> files) throws JsonProcessingException {
        chatHistoryService.saveIdList(chatId,"chat");
        List<Message> messages = chatMemory.get(chatId);
        List<MessageVo> list= messages.stream().map(MessageVo::new).toList();
        chatHistoryService.saveHistoryMessages(list, chatId, "chat");
        if (files== null|| files.isEmpty()){
            return chatClient.prompt()
                    .user(prompt)
                    .advisors(a->a.param(ChatMemory.CONVERSATION_ID,chatId))
                    .stream()
                    .content();
        }
        return multiModuleChat(prompt,chatId,files);

    }

    private Flux<String> multiModuleChat(String prompt, String chatId, List<MultipartFile> files) {
        //1.解析多媒体
        List<Media> medias = files.stream().map(file -> new Media(
                        MimeType.valueOf(Objects.requireNonNull(file.getContentType())),
                        file.getResource()
                )
        ).toList();
        return chatClient.prompt()
                .user(p->p.text(prompt).media(medias.toArray(Media[]::new)))
                .advisors(a->a.param(ChatMemory.CONVERSATION_ID,chatId))
                .stream()
                .content();
    }
}